<template>
  <chart :options="options" :auto-resize="autoResize" :theme="theme" :watch-shallow="watchShallow"
      :class="className" :style="{height:height,width:width}"></chart>
</template>

<script>

export default {
  props: {
    title: { type: String, default: '' },
    chartData: { type: Object },
    className: { type: String, default: 'chart' },
    theme: { type: String, default: 'macarons' },
    autoResize: { type: Boolean, default: true },
    watchShallow: { type: Boolean, default: true },
    width: { type: String, default: '100%' },
    height: { type: String, default: '260px' },
    lineColor: { type: String, default: '#5C5C5C' },
    areaColor: { type: String, default: '#8B8B83' }
  },
  data() {
    return {
      options: this.buildOptions(this.chartData)
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.options = this.buildOptions(val)
      }
    }
  },
  mounted() {
    if (!this.options && this.chartData) {
      this.options = this.buildOptions(this.chartData)
    }
  },
  methods: {
    buildOptions(chartData) {
      if (!chartData || !chartData.category || !chartData.valueBeans) {
        return
      }
      var category = chartData.category
      var unit = null
      chartData.valueBeans.map(item => {
        item.type = 'line'
        item.areaStyle = {}
        item.lineStyle = {
          color: this.lineColor
        }
        item.areaStyle = {
          color: this.areaColor
        }
        item.label = {
          normal: {
            show: true,
            position: 'bottom'
          }
        }
        item.markPoint = {
          data: [
            { type: 'max' },
            { type: 'min' }
          ]
        }
        item.markLine = {
          data: [
            { type: 'average', name: '平均值' }
          ]
        }
        unit = item.unit
      })
      var seriesData = chartData.valueBeans

      return {
        grid: {
          top: 10,
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{a}增量 <br/>{b}: {c}' + unit
        },
        xAxis: {
          type: 'category',
          data: category
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            show: true,
            formatter: '{value}' + unit
          }
        },
        series: seriesData
      }
    }
  }
}
</script>
